﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Client
{
   public class SingleObjManager
    {
      static Dictionary<Type, object> singleObjs;

       static SingleObjManager()
       {
           singleObjs = new Dictionary<Type, object>();
       }

       public static T GetSingleObj<T>()where T:new()
       {
           Type type = typeof(T);
           if (singleObjs.Keys.Contains(type))
           {
               return (T)singleObjs[type];
           }
           else
           {
               T t = new T();
               singleObjs.Add(type, t);
               Form form = t as Form;
               if (form != null)
                   form.FormClosed+= (sender,e) => {singleObjs.Remove(sender.GetType()); };
               return t;
           }
       }

       public static object GetSingleObj(Type type)
       {
           if (singleObjs.Keys.Contains(type))
           {
               return singleObjs[type];
           }
           else
           {
               object obj = Activator.CreateInstance(type);
               singleObjs.Add(type, obj);
               Form form =obj as Form;
               if (form != null)
                   form.FormClosed += (sender, e) => { singleObjs.Remove(sender.GetType()); };
               return obj;
           }
       }
    }
}
